<?php
/**
 * @file /Db/Adapter/mysql.php
 *
 * mysql-Adapter to database.
 *
 * Class that represents a connection to a MySQL-Database and uses the common
 * functions defined by Db_Interface.
 *
 * New BSD License
 * \n
 * Copyright (c) 2010 Rpd-Team
 *
 * @namespace  rpd
 * @since      0.0.1
 * @version    0.0.1
 */

/**
 *
 */

class Db_Adapter_mysql extends Db_Adapter implements Db_Adapter_Interface {
	
	private $_transaction = FALSE;

	public function connectionClose()
	{
		$this->_connectionOpen = false;
		mysql_close($this->_link);
	}
	
	public function connectionIsActive()
	{
		return $this->_connectionOpen;
	}
	
	function database($name) {
		return mysql_select_db($name, $this->_link);
	}
	
	function encoding($charset)
	{
		mysql_query("set character set '" . $charset . "'");
	}
	
	function errorCode()
	{
		return mysql_errno($this->_link);
	}
	
	function errorMessage()
	{
		return mysql_error($this->_link);
	}
	
	function getLinkId()
	{
		return $this->_link;
	}
	
	function lastInsertId()
	{
		return mysql_insert_id($this->_link);
	}
	
	function prepare($statement)
	{
		return new Db_Statement_mysql($statement, $this->_link);
	}

	function query($statement, $values = NULL)
	{
		$values = func_get_args();
		                            
		$result = new Db_Statement_mysql($statement, $this->_link);
		if ($values !== NULL)
		{
			$result->__invoke($values);
		}

		return $result;
	}
	
	function quote($unescaped)
	{
		if (is_scalar($unescaped_string))
		{
			if (is_string($unescaped))
			{
				return "'"
				     . mysql_real_escape_string($unescaped, $this->_link)
				     . "'";
			}
			else
			{
				return mysql_real_escape_string($unescaped, $this->_link);
			}
		}
		
		return $this->quote(serialize($unescaped));
	}
	
	function transactionBegin()
	{
		$this->_transaction = !$this->_transaction;
		return $this->query("START TRANSACTION");
	}
	
	function transactionCommit()
	{
		$this->_transaction = !$this->_transaction;
		return $this->query("COMMIT");
	}
	
	function transactionIsActive()
	{
		return $this->_transaction;
	}
	
	function transactionRollback()
	{
		$this->_transaction = !$this->_transaction;
		return $this->query("ROLLBACK");
	}

	function __construct($settings) {
		if ($settings["persistent"])
		{
			$this->_link = mysql_pconnect($settings["server"],
			                              $settings["user"],
			                              $settings["password"]);
		}
		else
		{
			$this->_link = mysql_connect($settings["server"],
			                             $settings["user"],
			                             $settings["password"]);
		}

		$this->database($settings["database"]);
	}

}

?>